package com.youxin.cpcenter.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.login.PayloadBean;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.BusinessDataException;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.common.redis.RedisOperator;
import com.youxin.foundation.utils.JsonUtils;
import com.youxin.foundation.utils.StringUtils;

public class CustomHandlerInterceptor extends HandlerInterceptorAdapter{
	protected static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(CustomHandlerInterceptor.class);

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
      //  System.out.println(">>>MyInterceptor2>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
        auth(request);        
        return true;// 只有返回true才会继续向下执行，返回false取消当前请求
    }
	/**
	 * 验证token
	 * @description 
	 * @param request HttpServletRequest
	 */
	private void auth(HttpServletRequest request){
		if("options".equalsIgnoreCase(request.getMethod()))
		{
			return;
		}
		
        String token =LoginAuth.getToken(request);
		PayloadBean payloadBean=LoginAuth.auth(token);
		//logger.warn("start:"+String.valueOf(token));
		if(payloadBean==null)
		{
			throw new BusinessDataException(BusinessMessages.LOGIN_INFO);
		}else if(payloadBean.hasExpires())
		{
			//logger.warn("payloadBean.hasExpires:"+String.valueOf(token));
			throw new BusinessDataException(BusinessMessages.TOKEN_EXPIRES);
		}else
		{
			long userid=payloadBean.getUserid();
			UserInfo userInfo=RedisOperator.getUserInfo(userid);
			if(userInfo==null||!(userid>0&&!StringUtils.isNullOrEmpty(userInfo.getUid())))
			{
				//logger.warn("userInfo=:"+JsonUtils.objectToFasterxmlJsonString(userInfo)+",token:"+String.valueOf(token));				
				throw new BusinessDataException(BusinessMessages.TOKEN_EXPIRES);
			}
			LoginAuth.initThreadContext(userInfo);
		}
	}
	
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
       // System.out.println(">>>MyInterceptor2>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    	LoginAuth.clear();
        //System.out.println(">>>MyInterceptor2>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }

    
}
